#include "chatuserwid.h"
#include <QMouseEvent>
#include <QPainter>
#include <QPixmap>
#include <QRectF>
#include "global.h"
#include "ui_chatuserwid.h"
ChatUserWid::ChatUserWid(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ChatUserWid)
    , _redPointVisible(false)
    , _friendInfo(nullptr)
{
    ui->setupUi(this);
}

ChatUserWid::~ChatUserWid()
{
    delete ui;
}

int ChatUserWid::uid() const
{
    return _friendInfo->uid;
}

QString ChatUserWid::name() const
{
    return _friendInfo->name;
}

void ChatUserWid::setRedPointVisible(bool visible)
{
    _redPointVisible = visible;
    update();
}

void ChatUserWid::setChatInfo(std::shared_ptr<FriendInfo> friendInfo)
{
    _friendInfo = friendInfo;
    if (!friendInfo->remark.isEmpty()) {
        ui->name_lb->setText(friendInfo->remark);
    } else {
        ui->name_lb->setText(friendInfo->name);
    }
    ui->lastMessage_lb->setText(friendInfo->last_msg);
    this->ui->lastTime_lb->setText(friendInfo->last_msg_time);
    ui->lastMessage_lb->setText(friendInfo->last_msg);
    if (friendInfo->icon.trimmed().isEmpty()) {
        friendInfo->icon = GetRandomIcon();
    }
    QPixmap p(friendInfo->icon);
    p = p.scaled(ui->icon_lb->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->icon_lb->setPixmap(p);
}

void ChatUserWid::paintEvent(QPaintEvent *event)
{
    QWidget::paintEvent(event);
    if (_redPointVisible) {
        qreal w = width();
        qreal h = height();
        QRectF rect(w * 0.7, h * 0.2, 8, 8);
        QPainter painter(this);
        painter.setBrush(Qt::red);
        painter.setPen(Qt::NoPen);
        painter.drawEllipse(rect);
    }
}

void ChatUserWid::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        emit sig_clicked(_friendInfo);
    }
    QWidget::mousePressEvent(event);
}
